import 'package:flutter/material.dart';
import '../video_player_controller.dart';

/// 默认视频控制层
class DefaultVideoControls extends StatefulWidget {
  final NativeAvPlayerController controller;

  const DefaultVideoControls({
    Key? key,
    required this.controller,
  }) : super(key: key);

  @override
  State<DefaultVideoControls> createState() => _DefaultVideoControlsState();
}

class _DefaultVideoControlsState extends State<DefaultVideoControls> {
  bool _isVisible = true;
  bool _isDragging = false;
  late Duration _dragPosition;

  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_onControllerUpdate);
    _dragPosition = Duration.zero;
  }

  @override
  void dispose() {
    widget.controller.removeListener(_onControllerUpdate);
    super.dispose();
  }

  void _onControllerUpdate() {
    if (mounted) {
      setState(() {});
    }
  }

  void _toggleVisibility() {
    setState(() {
      _isVisible = !_isVisible;
    });
  }

  void _togglePlayPause() {
    if (widget.controller.isPlaying) {
      widget.controller.pause();
    } else {
      widget.controller.play();
    }
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '$hours:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '$minutes:${twoDigits(seconds)}';
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _toggleVisibility,
      child: AnimatedOpacity(
        opacity: _isVisible ? 1.0 : 0.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.transparent,
                Colors.black.withOpacity(0.7),
              ],
            ),
          ),
          child: Column(
            children: [
              _buildTopBar(),
              const Spacer(),
              _buildBottomBar(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          // 返回按钮
          IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(Icons.arrow_back, color: Colors.white),
          ),
          const Spacer(),
          // 设置按钮
          IconButton(
            onPressed: _showSettingsMenu,
            icon: const Icon(Icons.settings, color: Colors.white),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    final position = _isDragging ? _dragPosition : widget.controller.position;
    final duration = widget.controller.duration;
    final progress = duration.inMilliseconds > 0
        ? position.inMilliseconds / duration.inMilliseconds
        : 0.0;

    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 进度条
          Row(
            children: [
              Text(
                _formatDuration(position),
                style: const TextStyle(color: Colors.white, fontSize: 12),
              ),
              Expanded(
                child: Slider(
                  value: progress.clamp(0.0, 1.0),
                  onChanged: _onSliderChanged,
                  onChangeStart: _onSliderChangeStart,
                  onChangeEnd: _onSliderChangeEnd,
                  activeColor: Theme.of(context).primaryColor,
                  inactiveColor: Colors.white.withOpacity(0.3),
                ),
              ),
              Text(
                _formatDuration(duration),
                style: const TextStyle(color: Colors.white, fontSize: 12),
              ),
            ],
          ),

          // 控制按钮行
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // 上一个按钮
              IconButton(
                onPressed: null, // TODO: 实现上一个功能
                icon: const Icon(Icons.skip_previous, color: Colors.white54),
              ),

              // 快退按钮
              IconButton(
                onPressed: _seekBackward,
                icon: const Icon(Icons.replay_10, color: Colors.white),
              ),

              // 播放/暂停按钮
              IconButton(
                onPressed: _togglePlayPause,
                icon: Icon(
                  widget.controller.isPlaying
                      ? Icons.pause_circle_filled
                      : Icons.play_circle_filled,
                  color: Colors.white,
                  size: 48,
                ),
              ),

              // 快进按钮
              IconButton(
                onPressed: _seekForward,
                icon: const Icon(Icons.forward_10, color: Colors.white),
              ),

              // 下一个按钮
              IconButton(
                onPressed: null, // TODO: 实现下一个功能
                icon: const Icon(Icons.skip_next, color: Colors.white54),
              ),

              // 全屏按钮
              IconButton(
                onPressed: () {
                  print(
                      'DefaultControls: 全屏按钮点击，当前状态: ${widget.controller.isFullScreen}');
                  widget.controller.toggleFullScreen();
                },
                icon: Icon(
                  widget.controller.isFullScreen
                      ? Icons.fullscreen_exit
                      : Icons.fullscreen,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _onSliderChanged(double value) {
    setState(() {
      _dragPosition = Duration(
        milliseconds:
            (value * widget.controller.duration.inMilliseconds).round(),
      );
    });
  }

  void _onSliderChangeStart(double value) {
    setState(() {
      _isDragging = true;
    });
  }

  void _onSliderChangeEnd(double value) {
    setState(() {
      _isDragging = false;
    });
    widget.controller.seekTo(_dragPosition);
  }

  void _seekBackward() {
    final newPosition =
        widget.controller.position - const Duration(seconds: 10);
    widget.controller
        .seekTo(newPosition < Duration.zero ? Duration.zero : newPosition);
  }

  void _seekForward() {
    final newPosition =
        widget.controller.position + const Duration(seconds: 10);
    final duration = widget.controller.duration;
    widget.controller.seekTo(newPosition > duration ? duration : newPosition);
  }

  void _showSettingsMenu() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.black87,
      builder: (context) => _buildSettingsPanel(),
    );
  }

  Widget _buildSettingsPanel() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 播放速度设置
          ListTile(
            leading: const Icon(Icons.speed, color: Colors.white),
            title: const Text('播放速度', style: TextStyle(color: Colors.white)),
            trailing:
                const Icon(Icons.arrow_forward_ios, color: Colors.white54),
            onTap: _showSpeedSelector,
          ),

          // 画质设置
          ListTile(
            leading: const Icon(Icons.high_quality, color: Colors.white),
            title: const Text('画质', style: TextStyle(color: Colors.white)),
            trailing:
                const Icon(Icons.arrow_forward_ios, color: Colors.white54),
            onTap: () {
              // TODO: 实现画质选择
              Navigator.pop(context);
            },
          ),

          // 字幕设置
          ListTile(
            leading: const Icon(Icons.subtitles, color: Colors.white),
            title: const Text('字幕', style: TextStyle(color: Colors.white)),
            trailing:
                const Icon(Icons.arrow_forward_ios, color: Colors.white54),
            onTap: () {
              // TODO: 实现字幕选择
              Navigator.pop(context);
            },
          ),
        ],
      ),
    );
  }

  void _showSpeedSelector() {
    Navigator.pop(context); // 关闭设置面板

    final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black87,
        title: const Text('播放速度', style: TextStyle(color: Colors.white)),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: speeds
              .map((speed) => ListTile(
                    title: Text(
                      '${speed}x',
                      style: const TextStyle(color: Colors.white),
                    ),
                    onTap: () {
                      widget.controller.setPlaybackSpeed(speed);
                      Navigator.pop(context);
                    },
                  ))
              .toList(),
        ),
      ),
    );
  }
}
